package auctionServer.businessLogic;

import auctionServer.io.IOManager;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;

public class Peer {
	private String nick;
	private DatagramSocket clientSocket;
	private int port;
	private String serverAddress;
	private boolean left;
	private ArrayList<String> offlineMessages;
    private boolean login;

    public Peer(String nick, int udpPortNumber, String serverAddress) {
		this.nick = nick;

		offlineMessages = new ArrayList<String>();
		
		newConnect(udpPortNumber,serverAddress);
        login = false;
	}

    public Peer(int udpPortNumber, String serverAddress) {
        offlineMessages = new ArrayList<String>();

        newConnect(udpPortNumber,serverAddress);
        login = false;
    }

    public void newConnect(int udpPortNumber, String serverAddress) {
		
		this.port = udpPortNumber;
		this.serverAddress = serverAddress;
		
		 if(clientSocket != null && clientSocket.isBound())
             clientSocket.close();
		try {
			clientSocket = new DatagramSocket();
		} catch (SocketException e) {
			IOManager.throwWarning("Peer socket connection problem. Unexpected situation.");
		}
	}

	public void stop() {
		clientSocket.close();
	}

	public String getNick() {
		return nick;
	}

	public void sendMessage(String string) {
		if(left){
			offlineMessages.add(string);
			return;
		}
		byte[] sendData = string.getBytes();
        DatagramPacket sendPacket;
		try {
			sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName(serverAddress), port);
			clientSocket.send(sendPacket);
		} catch (IOException e) {
			IOManager.throwWarning("Peer socket connection problem. Unexpected situation.");
		}
	}

	public void leaved() {
		left = true;
	}
	
	public void joined() {
		left = false;
		for (String message : offlineMessages) {
			sendMessage(message);
		}
		offlineMessages = new ArrayList<String>();
        login = true;
	}

    public boolean isLogin() {
        return login;
    }

    public int getPort() {
        return port;
    }

    public String getServerAddress() {
        return serverAddress;
    }

    public void setNick(String nick) {
        this.nick = nick;
    }

    public void logout() {
        login = false;
    }
}
